<template>
  <div class="pagination">
    <el-button :disabled="modelValue === 1" icon="ArrowLeft" @click="handlePrevPage"></el-button>
    <template v-if="totalPages <= 5">
      <el-button v-for="page in totalPages" :key="page" :disabled="modelValue === page"
        :class="{ active: modelValue === page }" @click="handlePageClick(page)">{{ page }}</el-button>
    </template>
    <template v-else>
      <el-button v-if="modelValue > 3" :class="{ active: modelValue === 1 }" @click="handlePageClick(1)">1</el-button>
      <template v-if="modelValue > 4">
        <span class="ellipsis">...</span>
      </template>
      <el-button v-for="page in visiblePages" :key="page" :disabled="modelValue === page"
        :class="{ active: modelValue === page }" @click="handlePageClick(page)">{{ page }}</el-button>
      <template v-if="modelValue < totalPages - 3">
        <span class="ellipsis">...</span>
      </template>
      <el-button v-if="modelValue < totalPages - 2" :class="{ active: modelValue === totalPages }"
        @click="handlePageClick(totalPages)">{{ totalPages }}</el-button>
    </template>
    <el-button :disabled="modelValue === totalPages" icon="ArrowRight" @click="handleNextPage"></el-button>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
const emits = defineEmits(['update:modelValue']);

const props = defineProps({
  modelValue: {
    type: Number,
    required: true
  },
  totalPages: {
    type: Number,
    required: true
  }
})
const visiblePages = computed(() => {
  const pages = []
  let start = Math.max(1, props.modelValue - 2)
  let end = Math.min(props.totalPages, start + 4)
  while (start <= end) {
    pages.push(start)
    start++
  }
  return pages
})
const handlePrevPage = () => {
  if (props.modelValue > 1) {
    emits('update:modelValue', props.modelValue - 1)
  }
}
const handleNextPage = () => {
  if (props.modelValue < props.totalPages) {
    emits('update:modelValue', props.modelValue + 1)
  }
}
const handlePageClick = (page) => {
  if (page !== props.modelValue) {
    emits('update:modelValue', page)
  }
}
watch(() => props.modelValue, (newValue, oldValue) => {
  if (newValue !== oldValue) {
    const diff = Math.abs(newValue - oldValue)
    if (diff > 2) {
      emits('update:modelValue', oldValue + Math.sign(newValue - oldValue) * 2)
    }
  }
})

</script>
<style scoped>
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 6px;
}

.el-button {
  margin: 0 5px;
  min-width: 32px;
}

.el-button.active {
  background-color: #409eff;
  color: #fff;
}

.ellipsis {
  margin: 0 5px;
}
</style>